// For hidden process
var canvasDivHidden = document.getElementById('canvasHidden');
canvasHidden = document.createElement('canvas');
canvasHidden.setAttribute('width', canvasWidth);
canvasHidden.setAttribute('height', canvasHeight);
canvasHidden.setAttribute('id', 'canvasHidden');
canvasDivHidden.appendChild(canvasHidden);
if(typeof G_vmlCanvasManager != 'undefined') {
	canvasHidden = G_vmlCanvasManager.initElement(canvasHidden);
}
contextHidden = canvasHidden.getContext("2d"); // Grab the 2d canvas context
// For hidden process


var current_shape = -1;
var drag_shape = false;
var choose_shape = '';
var insert_image = false;
var resize_shape = -1;
var stage = new Kinetic.Stage({
    container: 'canvasDiv2',
    width: canvasWidth,
    height: canvasHeight
  });
var mouseSX, mouseSY, mouseDX, mouseDY, osX, osY, match;
var layer = new Kinetic.Layer();
var mode_shape = '';
var resizeX, resizeY, resizing, rotateX, rotateY, rotating, rotateCX, rotateCY;
var current_tool_shape = '';
var img_shape = Array();
var maskm_shape = Array();
var maskb_shape = Array();
var tempImg_shape = Array();
// add the layer to the stage
stage.add(layer);

function drawshape(finished){
	if(mode_shape=='') return;

      layer.add(draw_shape);
      layer.draw();

      var shape = layer.get('Shape')[current_shape];
      if(finished==false) shape.remove();
      else{
	      event_shape(draw_shape);
      }
}
function event_shape(draw_shape){
	  draw_shape.on('mouseover', function() {
        document.body.style.cursor = 'pointer';
      });
      draw_shape.on('mouseout', function() {
        document.body.style.cursor = 'default';
      });
      draw_shape.on('mousedown', function(e) {
        choose_shape = $(this).context.attrs.name;
      	this.moveToTop();
        var ctx = layer.getContext();
	    var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
	    osX = osY = -1;
	    match = false;
	    if(get_pixel.data[3]<3){
	    	osX = $(this).context.attrs.x;
	    	osY = $(this).context.attrs.y;
	    }
      });
      draw_shape.on('mouseup', function() {
      	if(choose_shape!=''){
      		var x = $(this).context.attrs.x;
      		var y = $(this).context.attrs.y;
      		var cx = $(this).context.attrs.cx;
      		var cy = $(this).context.attrs.cy;
      		if(distance(x,y, cx,cy)< 15){
      			match = true;
      		}
      	}
      });
       draw_shape.on('mousemove', function() {
       	var ctx = layer.getContext();
	    var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
        if(get_pixel.data[3] > 3 && this.attrs.draggable == true) document.body.style.cursor = 'pointer';
        else document.body.style.cursor = 'default';
      });
      draw_shape.on('dragmove', function(e) {
	    if(osX!=-1&&osY!=-1){	
            this.attrs.x = osX;
            this.attrs.y = osY;
	    }
      });
      draw_shape.on('dragend', function(e) {
	    if(match){	
	    	this.setPosition(this.attrs.cx, this.attrs.cy);
  			this.moveToBottom();
  			this.setDraggable(false);
  			layer.draw();
	    }
	    var all_draggable_falsed = true;
	    for(var i=0;i<layer.get('Shape').length;i++){
	    	if(layer.get('Shape')[i].attrs.draggable==true){
	    		all_draggable_falsed = false;
	    	}
	    }
	    if(all_draggable_falsed==true) final_match();
      });
}
function final_match(){
	$.blockUI({css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        }});
    $.ajax({
        type: "POST",
        url: site_url + '/puzzle/',
        data: {
            all_match: true,
        }
    }).done(function(url) {
        $.unblockUI();
        $('.ok-buoc2').show();
    });
}
function find_angle(p0,p1,c) {
    var p0c = Math.sqrt(Math.pow(c.x-p0.x,2)+
                        Math.pow(c.y-p0.y,2)); // p0->c (b)   
    var p1c = Math.sqrt(Math.pow(c.x-p1.x,2)+
                        Math.pow(c.y-p1.y,2)); // p1->c (a)
    var p0p1 = Math.sqrt(Math.pow(p1.x-p0.x,2)+
                         Math.pow(p1.y-p0.y,2)); // p0->p1 (c)
    return Math.acos((p1c*p1c+p0c*p0c-p0p1*p0p1)/(2*p1c*p0c));
}

function merge_mask(img,maskm,maskb,shapeW,shapeH){
	var maskWidth = maskb.width;
	var maskHeight = maskb.height;
	var img_width = img.width;
	var img_height = img.height;
	var offsetX = 0;
	var offsetY = 0;
	canvasHidden.setAttribute('width', maskWidth);
	canvasHidden.setAttribute('height', maskHeight);
	contextHidden.clearRect(0, 0, maskWidth, maskHeight);
	contextHidden.drawImage(maskm, 0, 0, maskWidth, maskHeight);
	contextHidden.globalCompositeOperation = 'source-in';
	contextHidden.drawImage(img, offsetX, offsetY, img_width, img_height);
	contextHidden.globalCompositeOperation = 'source-over';
	contextHidden.drawImage(maskb, 0, 0, maskWidth, maskHeight);
	var maskLayerData = contextHidden.getImageData(0, 0, maskWidth, maskHeight);
	var imgtemp = document.createElement("img");
	var minX = maskWidth, minY = maskHeight;
	var maxX = 0, maxY = 0;
	var get_pixel = contextHidden.getImageData(0,0,maskWidth,maskHeight);
	for(var row = 0; row < maskHeight; row++) {
	    for(var col = 0; col < maskWidth; col++) {
	      if(get_pixel.data[(row * maskWidth + col) * 4 + 3]>3){
	      	if(minY >= row) minY = row;
	      	if(minX >= col) minX = col;
	      	if(maxY <= row) maxY = row;
	      	if(maxX <= col) maxX = col;
	      }
	    }
	  }
	imgtemp.src = canvasHidden.toDataURL("image/png");
	imgtemp.minX = minX;
	imgtemp.minY = minY;
	imgtemp.maxX = maxX;
	imgtemp.maxY = maxY;
	return imgtemp;
}
function randomFromInterval(from,to){
    return Math.floor(Math.random()*(to-from+1)+from);
}
function draw_mask_image(img,maskm,maskb,tempImg){
	if(choose_shape==''){
		var img_width = tempImg.maxX - tempImg.minX;
		var img_height = tempImg.maxY - tempImg.minY;

		img_shape["chenhinh-" + current_shape] = img;
		maskm_shape["chenhinh-" + current_shape] = maskm;
		maskb_shape["chenhinh-" + current_shape] = maskb;
		tempImg_shape["chenhinh-" + current_shape] = tempImg;
		
	  	var draw_shape = new Kinetic.Shape({
		    drawFunc: function(canvas) {
		    	var shapeX = this.attrs.shapeX;
		    	var shapeY = this.attrs.shapeY;
		    	var shapeH = this.attrs.shapeH;
		    	var shapeW = this.attrs.shapeW;

		        var context = canvas.getContext();

			    context.beginPath(); 
			    context.rect(0, 0, shapeW, shapeH);
			    context.drawImage(tempImg_shape[this.attrs.name], -tempImg_shape[this.attrs.name].minX, -tempImg_shape[this.attrs.name].minY, maskb.width, maskb.height);
			    context.closePath();
			    canvas.fillStroke(this);
		    },
		    shapeRotate: 0,
	        draggable: true,
	        shapeX: 0,
	        shapeY: 0,
	        shapeW: img_width,
	        shapeH: img_height,
	        x: randomFromInterval(0,tempImg.width-img_width),
	        y: randomFromInterval(540,640),
	        cx: 20+tempImg.minX,
	        cy: 23+tempImg.minY,
	        name : "chenhinh-" + current_shape,
		});

		layer.add(draw_shape);
	    layer.draw();
	    event_shape(draw_shape);
	    current_shape++;
		editing = true;
	}
	// }else{
	// 	img_shape[choose_shape] = img;
	// 	layer.draw();
	// }
}
function distance(x1,y1, x2,y2){
	return Math.sqrt(Math.pow(x2 - x1,2) + Math.pow(y2 - y1,2));
}
function check_drag(){
	var ctx = layer.getContext();
	var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
	if(get_pixel.data[3]==255||get_pixel.data[3]==2||get_pixel.data[3]==3) return true;
	else {
		choose_shape = '';
		return false;
	};
}
function check_resize(){
	var ctx = layer.getContext();
	var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
	resize_shape = -1;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==241) resize_shape = 1;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==242) resize_shape = 2;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==243) resize_shape = 3;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==244) resize_shape = 4;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==245) resize_shape = 5;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==246) resize_shape = 6;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==247) resize_shape = 7;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==248) resize_shape = 8;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==228&&get_pixel.data[2]==0) resize_shape = 9;
}
function switch_layer(){
	choose_shape = '';
	layer.draw();
	var ctx = layer.getContext();
	history.push(colorLayerData);
	tempLayerData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
	clearCanvasTransparent();
	context.drawImage(outlineImage, drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
	colorLayerData = context.getImageData(0, 0, canvasWidth, canvasHeight);
	mergeLayerShape();
	// mergeLayer();
	// mergeLayerKhungTranh();
	context.putImageData(colorLayerData, 0, 0);
	colorLayerData = context.getImageData(0, 0, canvasWidth, canvasHeight);
	layer.remove();
	layer = new Kinetic.Layer();
	stage.add(layer);
	current_shape = -1;
	img_shape = Array();
	$('#canvasDiv2').css('display','none');
}
    // Add mouse events
	// ----------------
$('#canvasDiv2').mousedown(function(e)
{	
	e.originalEvent.preventDefault();
	if(toolChoose<=0||mode_shape=='') return;


	mouseDX = mouseSX = mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseDY = mouseSY = mouseY = e.pageY - this.offsetTop;
	drag_shape = check_drag();

	if(curTool=='shape' && drag_shape==false){
		current_shape++;
		shapeX = mouseX;
		shapeY = mouseY;
	}
	if(drag_shape==false) paint = true;
});

$('#canvasDiv2').mousemove(function(e){
	mouseSX = mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseSY = mouseY = e.pageY - this.offsetTop;
	
	if(toolChoose<=0) return;

	if(paint==true){
		
		if(curTool=='shape'){
			shapeW = mouseX - shapeX;
			shapeH = mouseY - shapeY;
		}
		drawshape(false);
	}
});

$('#canvasDiv2').mouseup(function(e){
	if(toolChoose<=0) return;
	if(document.body.style.cursor=='default' && !$('.input-text').hasClass('active')){
  		choose_shape = '';
  		layer.draw();
  		paint = false;
  		editing = true;
  		return;
	}
	mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseY = e.pageY - this.offsetTop;

  	if(drag_shape==false && paint==true && (mouseX!=mouseDX||mouseY!=mouseDY)) drawshape(true);
  	if(mouseX==mouseDX&&mouseY==mouseDY && drag_shape==false) {
  		current_shape--;
  		choose_shape = '';
  		layer.draw();
  	}
	paint = false;
	editing = true;
});


$('#canvasDiv2').mouseleave(function(e){
	if(toolChoose<=0) return;
  	if(drag_shape==false && paint==true && (mouseX!=mouseDX||mouseY!=mouseDY)) drawshape(true);
  	if(mouseX==mouseDX&&mouseY==mouseDY && drag_shape==false) {
  		current_shape--;
  		choose_shape = '';
  		layer.draw();
  	}
	paint = false;
});

$(document).on('keydown',function(e){
	if(e.keyCode==46 && choose_shape!='' && !$('.input-text').hasClass('active')){
		var shape = layer.get('.'+choose_shape)[0];
		shape.remove();
		choose_shape='';
		layer.draw();
	}
});